#include "socket_basic.hpp"

class UDPServer : public socket_basic
{
public:
    UDPServer(uint16_t port) : socket_basic(port,INADDR_ANY)
    {
        ssize_t n = bind(_sockfd,reinterpret_cast<const sockaddr*>(&_addr),sizeof(_addr));
    }
    void Start()
    {
        while (true)
        {
            socklen_t size = sizeof(_addr);
            char buffer[1024];
            memset(static_cast<void*>(buffer),0,sizeof(buffer));
            ssize_t n = recvfrom(_sockfd, buffer, 1024, MSG_WAITALL, reinterpret_cast<sockaddr*>(&_addr), &size);
            if (n > 0)
            {
                std::cout << "receipt message:" << buffer << std::endl;
                socklen_t addr_len = sizeof(_addr);
                n = sendto(_sockfd,buffer,strlen(buffer),0,reinterpret_cast<const sockaddr*>(&_addr),addr_len);
            }
            sleep(1);


        }
    }

private:
};
void Usage(std::string use)
{
    std::cout << "Usage:\n\r " <<" "<< use << " " << "local_port" << std::endl;
}

int main(int argc, char *argv[])
{
    if (argc != 2)
    {
        Usage(argv[0]);
        exit(-1);
    }
    uint16_t port = static_cast<uint16_t>(std::stoi(argv[1]));

    UDPServer udp(port);

    udp.Start();
    return 0;
}